package cn.edu.cqvie.atc.sort.impl;

import cn.edu.cqvie.atc.sort.Sort;

import java.util.Comparator;

/**
 * Tim排序，归并排序
 *
 * @author Zheng Shaohong
 */
public class TimSort<T> extends BaseSort<T> {


    public static void main(String[] args) {
        Integer[] arr = new Integer[]{23, 12, 8, 0, 18, 90, 1, 2, 3};

        Sort<Integer> s = new TimSort<>();
        s.display(arr);
        s.sort(arr, new IntegerComparator());
        s.display(arr);
    }

    @Override
    public String toString() {
        return super.toString();
    }

    public T[] sort(T[] a, int low, int high) {
        int mid = (low + high) / 2;
        if (low < high) {
            sort(a, low, mid);
            sort(a, mid + 1, high);
            //左右归并
            merge(a, low, mid, high);
        }
        return a;
    }

    public void merge(T[] a, int low, int mid, int high) {
        T[] temp = (T[]) new Object[high - low + 1];
        int i = low;
        int j = mid + 1;
        int k = 0;
        // 把较小的数先移到新数组中
        while (i <= mid && j <= high) {
            if (c.compare(a[i], a[j]) < 0) {
                temp[k++] = a[i++];
            } else {
                temp[k++] = a[j++];
            }
        }
        // 把左边剩余的数移入数组
        while (i <= mid) {
            temp[k++] = a[i++];
        }
        // 把右边边剩余的数移入数组
        while (j <= high) {
            temp[k++] = a[j++];
        }
        // 把新数组中的数覆盖nums数组
        for (int x = 0; x < temp.length; x++) {
            a[x + low] = temp[x];
        }
    }

    @Override
    public void sort(T[] arr, Comparator<T> c) {
        super.c = c;
        sort(arr, 0, arr.length - 1);
    }
}
